package com.example.helper2;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.MessageQueue;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.media.audiofx.Visualizer.ERROR;

public class fragment_user_message extends Fragment implements View.OnClickListener {
    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager layoutManager;

    // 发送按钮
    private Button send;
    // 爱心按钮
    private ImageButton like;
    // 用户留言内容
    private EditText user_msg;

    private List<UserMsgInfo> myDataset = new ArrayList<>();

    Handler handler1 = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            int id = data.getInt("id");
            String user_name = data.getString("user_name");
            String user_word = data.getString("user_word");
            String user_msg = data.getString("user_msg");
            int like_num = data.getInt("like_num");
            Log.v("mydata","id："+id+" "+"user_name："+user_name+" "+"user_word："+user_word);
            myDataset.add(new UserMsgInfo(id,user_name,user_word,user_msg,like_num));

            Collections.sort(myDataset, new Comparator<UserMsgInfo>() {
                @Override
                public int compare(UserMsgInfo o1, UserMsgInfo o2) {
                    return new Double(o2.getNum()).compareTo(new Double(o1.getNum()));
                }
            });

            // 用数据去填充适配器
            mAdapter = new user_message_adapter(myDataset);
            // 创建一个新的布局管理器
            layoutManager = new LinearLayoutManager(getActivity());
            // 设置recyclerView的布局方式
            recyclerView.setLayoutManager(layoutManager);
            // 设置适配器
            recyclerView.setAdapter(mAdapter);

            Log.v("查看data的最终值：",myDataset.toString());
            //
            // TODO: 更新界面
            //
//            Log.i("mylog","请求结果-->" + val);
        }
    };


    Handler handler2 = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 200){
                Toast.makeText(getActivity(),"留言成功！",Toast.LENGTH_SHORT).show();
            }else if(msg.what == 201){
                String failInfo = (String)msg.obj;
                Toast.makeText(getActivity(),"留言失败！\n"+"原因可能是："+failInfo,Toast.LENGTH_SHORT).show();
            }
        }
    };


    // 用户基本信息的初始化，根据本地保存的信息来
    private TextView user_name;
    private TextView user_word;
    private TextView user_tel;
    private TextView user_addr;

    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        // 展示布局
        View view = inflater.inflate(R.layout.user_message,container,false);
        // 获取用户基本信息
        getUserInfo(view);

        // 获取recyclerview组件
        recyclerView = view.findViewById(R.id.user_recyclerview);
        // 获取用户输入的信息
        user_msg = view.findViewById(R.id.user_msg);
        // 获取发送按钮
        send = view.findViewById(R.id.send);
        // 获取点击like按钮
        //like = view.findViewById(R.id.like_icon_off);
        // 监听点击
        //like.setOnClickListener(this);
        send.setOnClickListener(this);
        // 添加分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
        // new一个新对象
        myDataset = new ArrayList<>();

        // 网络请求获取数据
        updateMessage();

        return view;
    }

    // 获取用户基本信息
    private void getUserInfo(View view){
        user_name = view.findViewById(R.id.user_name);
        user_word = view.findViewById(R.id.user_word);
        user_tel = view.findViewById(R.id.user_tel);
        user_addr = view.findViewById(R.id.user_address);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        String my_userName = sharedPreferences.getString("user_name",null);
        if (my_userName != null && my_userName.length() != 0){
            my_userName = user_name.getText().toString() + my_userName;
            user_name.setText(my_userName);
            String userWord = user_word.getText().toString() + sharedPreferences.getString("user_word",null);
            String userPhone = user_tel.getText().toString() + sharedPreferences.getString("user_phone",null);
            String userAddr = user_addr.getText().toString() + sharedPreferences.getString("user_address",null);
            user_word.setText(userWord);
            user_tel.setText(userPhone);
            user_addr.setText(userAddr);
        }
    }

    private void updateMessage() {
        myDataset = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String url_s = "http://wolfdnd.top:2020/";
                    URL url = new URL(url_s);
                    HttpURLConnection myconnect = (HttpURLConnection)url.openConnection();
                    // 设置请求方式
                    myconnect.setRequestMethod("GET");
                    myconnect.setConnectTimeout(5000);
                    myconnect.connect();
                    // 获取数据
                    if(myconnect.getResponseCode() == 200){
                        InputStream inputStream = myconnect.getInputStream();
                        InputStreamReader input = new InputStreamReader(inputStream);
                        BufferedReader buffer = new BufferedReader(input);
                        String inputLine;
                        StringBuffer resultData  = new StringBuffer();//StringBuffer字符串拼接很快
                        while((inputLine = buffer.readLine())!= null){
                            resultData.append(inputLine);
                        }
                        String text = resultData.toString();
                        parseJson(text);
//                        Log.v("out---------------->",text);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            // 解析json格式的数据
            private void parseJson(String text){
                try {
                    JSONArray jsonArray = new JSONArray(text);
                    int length = jsonArray.length();
                    String test;
                    for(int i=0; i < length; i++){
                        JSONObject userMsg = jsonArray.getJSONObject(i);
                        Log.v("查看记录",userMsg.toString());
                        int id = userMsg.getInt("id");
                        String user_name = userMsg.getString("user_name");
                        String user_word = userMsg.getString("user_word");
                        String user_msg = userMsg.getString("user_msg");
                        int like_num = userMsg.getInt("like_num");

                        Message msg = new Message();
                        Bundle data = new Bundle();
                        data.putInt("id",id);
                        data.putString("user_name",user_name);
                        data.putString("user_word",user_word);
                        data.putString("user_msg",user_msg);
                        data.putInt("like_num",like_num);
                        msg.setData(data);
                        handler1.sendMessage(msg);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void onClick(View view){

        switch (view.getId()){
            case R.id.send:
                SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user",Context.MODE_PRIVATE);
                final String userName = sharedPreferences.getString("user_name",null);
                if (userName == null || userName.length() == 0){
                    Toast.makeText(getActivity(),"请先登录！",Toast.LENGTH_SHORT).show();
                }else{
                    final String userWord = sharedPreferences.getString("user_word",null);
                    final String userMsg = user_msg.getText().toString();
                    // post请求发送留言
                    Log.v("是否点击鼠标","你点击了发送");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // 访问的服务器地址
                                String url_s = "http://wolfdnd.top:2020/";
                                // 创建一个URL对象
                                URL url = new URL(url_s);
                                // HTTP连接
                                HttpURLConnection mypost = (HttpURLConnection)url.openConnection();
                                // POST请求
                                mypost.setRequestMethod("POST");
                                // 设置字符集为UTF-8
                                mypost.setRequestProperty("Charset","UTF-8");
                                // 设置内容的格式
                                mypost.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                                mypost.setConnectTimeout(5000);
                                // 开启输出流
                                mypost.setDoOutput(true);

//                    String user_name = "我是用户名";
//                    String user_word = "我是励志语";
//                    String user_msg = "我的留言内容";

                                // 增加一个behavior字段
                                // 当behavior为‘like’时，进行点赞操作
                                // 除此之外，均为添加留言操作
                                String behavior = "msg";
                                // 待传送的数据，form格式
                                String data = "user_name="+ URLEncoder.encode(userName)+
                                        "&user_word="+URLEncoder.encode(userWord)+
                                        "&user_msg="+URLEncoder.encode(userMsg)+
                                        "&behavior="+URLEncoder.encode(behavior);
                                mypost.setRequestProperty("Content-Length",data.length()+"");
                                // 开始连接服务器
                                mypost.connect();
                                OutputStream out = mypost.getOutputStream();
                                out.write(data.getBytes());
                                out.flush();
                                out.close();


                                int code = mypost.getResponseCode();
                                if(code == 200 && (url.toString().equals(mypost.getURL().toString()))){// 成功提交
                                    Message success = new Message();
                                    success.what = 200;
                                    handler2.sendMessage(success);
                                    Log.v("留言是否成功","留言成功");
                                    // 刷新列表数据
                                    updateMessage();
                                }else{// 提交失败
                                    String res;
                                    try {
                                        InputStream in = mypost.getInputStream();
                                        int n;
                                        StringBuilder sb = new StringBuilder();
                                        while ((n=in.read()) != -1){
                                            sb.append((char)n);
                                        }
                                        res = sb.toString();

                                        Message fail = new Message();
                                        fail.what = 201;
                                        fail.obj = res;
                                        handler2.sendMessage(fail);

                                        Log.v("post请求失败返回信息",res);
                                        Log.v("留言是否成功","留言失败");

                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }

                                }

                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    // 失去输入框焦点
                    user_msg.clearFocus();
                    // 隐藏输入框
                    InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(user_msg.getWindowToken(),0);
                }
                break;
        }

    }


}
